package ua.edu.onu.ua;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.Deflater;

/**
 * Created by Student on 05.12.2014.
 */
public class packer {
    private static void pack(String[] filesToZip,
                             String zipFileName, byte[] buffer) {
        try {
            ZipOutputStream jos =

                    new ZipOutputStream(

                            new FileOutputStream(zipFileName));
            if(new File(zipFileName).exists()){
                System.out.println("This zip already exist, it will be rewrite");
            }
            jos.setLevel(Deflater.DEFAULT_COMPRESSION);
            for (int i = 0; i < filesToZip.length; i++) {
                System.out.println(i);
                jos.putNextEntry(new ZipEntry(filesToZip[i]));
                FileInputStream in =
                        new FileInputStream(filesToZip[i]);
                int len;
                while ((len = in.read(buffer)) > 0)
                    jos.write(buffer, 0, len);
                jos.closeEntry();
                in.close();
            }
            jos.close();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            System.err.println("Некорректный аргумент");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("Файл не найден");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Ошибка доступа");
        }
    }

    public static void main(String[] args) {
        System.out.println("Создание zip-архива");
        String[] filesToZip = new String[2];
        filesToZip[0] = "tozip.doc";
        byte[] buffer = new byte[1024];
        String zipFileName = "example.zip";
        pack(filesToZip, zipFileName, buffer);
    }
}